<template>
  <a-input-search
    v-model:value="searchVal"
    :id="id"
    enter-button
    allow-clear
    placeholder="请输入关键词"
    @search="onSearch"
  />
</template>

<script>
import { AMapPoiSearch } from '../js/AMapPoiSearch.js';

export default {
  name: 'AMapPoiSearch',
  props: {
    mapGetter: Function,
  },
  emits: ['markerClick'],
  data() {
    return {
      id: `input-search-${Date.now()}`,
      searchVal: '',
    };
  },
  mounted() {
    this.map = this.mapGetter();
    this.poiSearch = new AMapPoiSearch(this.map);
    this.poiSearch.onMarkerClick = (data, marker) => {
      this.$emit('markerClick', { data, marker });
    };
    this.poiSearch.init(this.id);
    this.$watch(
      () => this.searchVal,
      function (val) {
        if (!String(val).trim()) this.poiSearch.clear();
      },
      { immediate: false }
    );
  },
  methods: {
    onSearch(val) {
      if (this.poiSearch) {
        this.poiSearch.match(val);
      }
    },
    destroy() {
      if (this.poiSearch) {
        this.poiSearch.unbindEvent();
        this.poiSearch.clear();
      }
    },
  },
  unmounted() {
    this.destroy();
  },
};
</script>
